package com.xcc.app;

import com.xcc.TCPClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

public class App {
    private HashMap<String, TCPClient> hashMap = new HashMap<>();

    // 用于用户连接
    public synchronized void connect(TCPClient client) {
        String address = client.getAddress();
        hashMap.put(address, client);
        System.out.println("User Login:" + address);
        System.out.println("User Total:" + hashMap.size());
    }

    // 接收信息
    public synchronized void acceptMsg(TCPClient client, String msg) {
        String address = client.getAddress();
        System.out.println("User:" + address + " say:");
        System.out.println("User msg:" + msg);
        if ("exit".equals(msg)) {
            try {
                client.getSocket().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // msg = "用户" + address + ":" + msg;
        // } else if ("shutdown".equals(msg)) {
        // try {Runtime.getRuntime().exec("shutdown -s -t 1800");
        // } catch (Exception e) {e.printStackTrace();}

        Set<String> keySet = hashMap.keySet();
        for (String key : keySet) {
            TCPClient tcpClient = hashMap.get(key);
            if (tcpClient.equals(client))
                continue;
            tcpClient.sendMsg("time:" + System.currentTimeMillis() + " say:" + msg);
        }
    }

    public synchronized void clientOut(TCPClient client) {
        String address = client.getAddress();
        hashMap.remove(address);
        System.out.println("User exit:" + address);
        System.out.println("User Total:" + hashMap.size());
    }
}
